properties([
   parameters([
      string(name: 'MAX_WORKES_PER_NODE', defaultValue: '500', description: ''),
      booleanParam(name: 'SKIP_BUILD_MANIFEST', defaultValue: false, description: 'Ignore Build Manifest, Use The Previouse One'),
      booleanParam(name: 'SKIP_DISTRIBUTE', defaultValue: false, description: 'Ignore Ditribute Task')
    ])
 ])

def projectName = 'Chijin'
def originProjectDir = config.mountProjectDir(projectName)
// 所有玩家都能读出来的路径，会写进 distribute.manifest 中
def workerProjectDir = config.projectDir(projectName);

node('master')
{
   stage("Prepare")
   {
      // 挂载Z盘
      bat "if not exist z:\\ ( net use z: ${config.mountDir()} /y)"

      // 创建Log目录
      def logDir = "${originProjectDir}\\${config.distributeLogDir()}"
      bat "if not exist ${logDir} ( mkdir ${logDir} )"

      // 拷贝unity程序
      config.copyUnityDir()

      // 开始前，删除所有可能因上次编译错误或者手动停止的lock
      utils.deleteAllLockFiles(projectName)
   }

   stage('Master: Build Manifest')
   {
      if(params.SKIP_BUILD_MANIFEST == false)
      {
         def logDir = "${originProjectDir}\\${config.distributeLogDir()}"
         def logFilePath = "${logDir}\\distribute${config.buildName()}.log"

         def forceRebuild = ""
         if(params.FORCE_REBUILD)
         {
            forceRebuild = " -forceRebuild "
         }

         bat "${config.localUnityPath()} -quit -batchmode -projectPath ${originProjectDir} -target StandaloneWindows64 -graph Assets/AssetGraph.asset -executeMethod UnityEngine.AssetGraph.CUIUtility.BuildFromCommandline -logfile ${logFilePath} -distributedMaster ${workerProjectDir}"
      }
   }

   stage('Master: Distribute Tasks')
   {
      if(params.SKIP_DISTRIBUTE == false)
      {
         // 读清单文件，以获得要编译的ab包数量（即work数量）
         def mainfestFile = "${originProjectDir}\\distribute.manifest"
         datas = readYaml (file: "${mainfestFile}")

         int paramsWorkesPerNode = params.MAX_WORKES_PER_NODE
         utils.distributeTask(projectName, 'chijin-ab-on-windows-worker', datas.WorkCount, paramsWorkesPerNode)
      }
   }
}
